<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品管理</title>
    <script src="../../js/vue.js"></script>
    <link type="text/css" rel="stylesheet" href="../../css/index.css">
    <script src="../../js/index.js"></script>
    <script src="../../js/axios.min.js"></script>
    <style>
        .el-table .el-table__fixed-right {
            height: 100% !important;
        }
        .el-row {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
<div id="app" class="app1">
    <!--布局/搜索功能-->
    <el-row>
        <el-col :span="4">
            <el-input size="mini" v-model="searchForm.productCode" placeholder="商品编码"></el-input>
        </el-col>
        <el-col :span="4">
            <el-input size="mini" v-model="searchForm.productName" placeholder="商品名称"></el-input>
        </el-col>
        <el-col :span="4">
            <el-select size="mini" v-model="searchForm.categoryId" placeholder="商品分类" clearable>
                <el-option
                        v-for="item in categoryList"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        :value="item.categoryId">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="4">
            <el-select size="mini" v-model="searchForm.brandId" placeholder="商品品牌" clearable>
                <el-option
                        v-for="item in brandList"
                        :key="item.brandId"
                        :label="item.brandName"
                        :value="item.brandId">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="4">
            <el-select size="mini" v-model="searchForm.varietyId" placeholder="商品品种" clearable>
                <el-option
                        v-for="item in varietyList"
                        :key="item.varietyId"
                        :label="item.varietyName"
                        :value="item.varietyId">
                </el-option>
            </el-select>
        </el-col>
        <!-- 添加产地筛选 -->
        <el-col :span="4">
            <el-select size="mini" v-model="searchForm.originId" placeholder="商品产地" clearable>
                <el-option
                        v-for="item in originList"
                        :key="item.originId"
                        :label="item.originName"
                        :value="item.originId">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="4">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            &nbsp;&nbsp;
            <el-button size="mini" type="primary" @click="handleAdd">添加</el-button>
        </el-col>
    </el-row>

    <!--列表-->
    <el-table :data="tableData" style="width: 100%" height="500" border>
        <el-table-column prop="productId" label="商品ID" width="100"></el-table-column>
        <el-table-column prop="productCode" label="商品编码" width="120"></el-table-column>
        <el-table-column prop="productName" label="商品名称" width="150"></el-table-column>
        <!--<el-table-column prop="categoryName" label="分类名称" width="120"></el-table-column>
        <el-table-column prop="unitName" label="单位名称" width="100"></el-table-column>
        <el-table-column prop="brandName" label="品牌名称" width="120"></el-table-column>
        <el-table-column prop="specName" label="规格名称" width="120"></el-table-column>-->
        <!-- 修改表格中的列，使用对象属性访问 -->
        <el-table-column prop="category.categoryName" label="分类名称" width="120"></el-table-column>
        <el-table-column prop="unit.unitName" label="单位名称" width="100"></el-table-column>
        <el-table-column prop="brand.brandName" label="品牌名称" width="120"></el-table-column>
        <el-table-column prop="variety.varietyName" label="品种名称" width="120"></el-table-column>
        <!-- 添加产地名称列 -->
        <el-table-column prop="origin.originName" label="产地名称" width="120"></el-table-column>
        <!-- 添加等级名称列 -->
        <el-table-column prop="grade.gradeName" label="等级名称" width="120"></el-table-column>
        <!-- 添加冷藏方式名称列 -->
        <el-table-column prop="cold.coldName" label="冷藏方式" width="120"></el-table-column>

        <!-- 修改表格中的规格名称列 -->
        <!--        <el-table-column prop="spec.specName" label="规格信息" width="120">
                    <template slot-scope="scope">
                        {{ getSpecNameFromJson(scope.row.specJson) }}
                    </template>-->
        <el-table-column label="规格信息" width="180">
            <template slot-scope="scope">
                <!-- 先显示规格名称，再显示规格值 -->
                <div v-if="getSpecData(scope.row.specJson)">
                    <div>规格：{{ getSpecData(scope.row.specJson).specName }}</div>
                    <div>值：{{ getSpecData(scope.row.specJson).specValue }}</div>
                </div>
                <div v-else>无规格</div>
            </template>
        </el-table-column>
        </el-table-column>
        <el-table-column prop="minOrderQuantity" label="最小起订量" width="100"></el-table-column>
        <el-table-column prop="price" label="参考价格" width="100"></el-table-column>
        <el-table-column prop="imageUrl" label="商品图片" width="120">
            <template slot-scope="scope">
                <img v-if="scope.row.imageUrl" :src="scope.row.imageUrl" style="width: 50px; height: 50px; object-fit: cover;">
            </template>
        </el-table-column>
        <el-table-column prop="description" label="商品描述" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
            <template slot-scope="scope">
                <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="delFlag" label="删除标志" width="100">
            <template slot-scope="scope">
                <el-tag :type="scope.row.delFlag === '0' ? 'success' : 'danger'">
                    {{ scope.row.delFlag === '0' ? '存在' : '删除' }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
            <template slot-scope="scope">
                {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ').substring(0, 19) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="更新者" width="100"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160">
            <template slot-scope="scope">
                {{ scope.row.updateTime ? scope.row.updateTime.replace('T', ' ').substring(0, 19) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,5,10,15,20,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!--添加/更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="800px">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="商品编码" prop="productCode">
                        <el-input v-model="form.productCode" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商品名称" prop="productName">
                        <el-input v-model="form.productName" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="商品分类" prop="categoryId">
                        <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                            <el-option
                                    v-for="item in categoryList"
                                    :key="item.categoryId"
                                    :label="item.categoryName"
                                    :value="item.categoryId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商品单位" prop="unitId">
                        <el-select v-model="form.unitId" placeholder="请选择单位" style="width: 100%">
                            <el-option
                                    v-for="item in unitList"
                                    :key="item.unitId"
                                    :label="item.unitName"
                                    :value="item.unitId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="商品品牌" prop="brandId">
                        <el-select v-model="form.brandId" placeholder="请选择品牌" style="width: 100%">
                            <el-option
                                    v-for="item in brandList"
                                    :key="item.brandId"
                                    :label="item.brandName"
                                    :value="item.brandId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!-- 在品牌选择后添加品种选择 -->
                <el-col :span="12">
                    <el-form-item label="商品品种" prop="varietyId">
                        <el-select v-model="form.varietyId" placeholder="请选择品种" style="width: 100%">
                            <el-option
                                    v-for="item in varietyList"
                                    :key="item.varietyId"
                                    :label="item.varietyName"
                                    :value="item.varietyId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 添加产地选择 -->
                <el-col :span="12">
                    <el-form-item label="商品产地" prop="originId">
                        <el-select v-model="form.originId" placeholder="请选择产地" style="width: 100%">
                            <el-option
                                    v-for="item in originList"
                                    :key="item.originId"
                                    :label="item.originName"
                                    :value="item.originId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <!-- 添加等级选择 -->
                <el-col :span="12">
                    <el-form-item label="商品等级" prop="gradeId">
                        <el-select v-model="form.gradeId" placeholder="请选择等级" style="width: 100%">
                            <el-option
                                    v-for="item in gradeList"
                                    :key="item.gradeId"
                                    :label="item.gradeName"
                                    :value="item.gradeId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 添加冷藏方式选择 -->
                <el-col :span="12">
                    <el-form-item label="冷藏方式" prop="coldId">
                        <el-select v-model="form.coldId" placeholder="请选择冷藏方式" style="width: 100%">
                            <el-option
                                    v-for="item in coldList"
                                    :key="item.coldId"
                                    :label="item.coldName"
                                    :value="item.coldId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="商品规格" prop="specId">
                        <el-select v-model="selectedSpecId" placeholder="请选择规格" style="width: 100%" @change="handleSpecChange">
                            <el-option
                                    v-for="item in specList"
                                    :key="item.specId"
                                    :label="item.specName"
                                    :value="item.specId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="selectedSpecValues.length > 0">
                    <el-form-item label="规格值" prop="specValue">
                        <el-select v-model="selectedSpecValue" placeholder="请选择规格值" style="width: 100%">
                            <el-option
                                    v-for="value in selectedSpecValues"
                                    :key="value"
                                    :label="value"
                                    :value="value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="最小起订量" prop="minOrderQuantity">
                        <el-input v-model="form.minOrderQuantity" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="参考价格" prop="price">
                        <el-input v-model="form.price" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="form.status" style="width: 100%">
                            <el-option label="正常" value="0"></el-option>
                            <el-option label="停用" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="删除标志" prop="delFlag">
                        <el-select v-model="form.delFlag" style="width: 100%">
                            <el-option label="存在" value="0"></el-option>
                            <el-option label="删除" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="商品图片">
                <el-upload
                        class="upload-demo"
                        action="/vegetablemarketexpress/product/uploadProductImage"
                        name="pic"
                        :on-success="handleImageSuccess"
                        :on-error="handleImageError"
                        :before-upload="beforeImageUpload"
                        :limit="1"
                        :file-list="imageFileList"
                        list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
                </el-upload>
                <el-input v-model="form.imageUrl" type="hidden"></el-input>
                <div v-if="form.imageUrl">
                    <img :src="form.imageUrl" style="width: 100px; height: 100px; margin-top: 10px;" />
                </div>
            </el-form-item>


            <el-form-item label="商品描述">
                <el-input type="textarea" v-model="form.description" autocomplete="off" :rows="3"></el-input>
            </el-form-item>

            <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark" autocomplete="off" :rows="2"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [], // 表格数据
                currentPage: 1, // 当前页码
                pageSize: 10, // 每页显示的条数
                total: 0, // 分页数据的总数
                searchForm: {}, // 搜索条件
                title: '添加商品', // 对话框标题
                dialogFormVisible: false, // 对话框是否可见

                // 属性列表数据
                categoryList: [],
                brandList: [],
                unitList: [],
                specList: [],
                varietyList: [],// 商品种类列表
                originList: [], // 产地列表
                gradeList: [],  // 等级列表
                coldList: [],   // 冷藏方式列表
                selectedSpecId: '', // 选中的规格ID
                selectedSpecValues: [], // 选中的规格值列表
                selectedSpecValue: '', // 选中的规格值
                imageFileList: [],// 图片文件列表

                form: {
                    productId: '',
                    productCode: '',
                    productName: '',
                    categoryId: '',
                    unitId: '',
                    brandId: '',
                    varietyId: '',
                    originId: '',
                    gradeId: '',
                    coldId: '',
                    specId: '', // 规格ID（用于关联，非JSON字段）
                    minOrderQuantity: '',
                    price: '',
                    imageUrl: '',
                    description: '',
                    status: '0',
                    delFlag: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                },
                rules: {
                    productCode: [
                        { required: true, message: '请输入商品编码', trigger: 'blur' }
                    ],
                    productName: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' }
                    ],
                    categoryId: [
                        { required: true, message: '请选择商品分类', trigger: 'change' }
                    ],
                    unitId: [
                        { required: true, message: '请选择商品单位', trigger: 'change' }
                    ],
                    brandId: [
                        { required: true, message: '请选择商品品牌', trigger: 'change' }
                    ],
                    originId: [
                        { required: true, message: '请选择商品产地', trigger: 'change' }
                    ],
                    gradeId: [
                        { required: true, message: '请选择商品等级', trigger: 'change' }
                    ],
                    coldId: [
                        { required: true, message: '请选择冷藏方式', trigger: 'change' }
                    ],
                    price: [
                        { required: true, message: '请输入参考价格', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.loadData();
            this.loadCategoryList();
            this.loadBrandList();
            this.loadUnitList();
            this.loadSpecList();
            this.loadVarietyList();
            this.loadOriginList(); // 加载产地列表
            this.loadGradeList();  // 加载等级列表
            this.loadColdList();   // 加载冷藏方式列表
        },
        methods: {
            // 加载商品数据
            loadData() {
                let _this = this;
                axios.post('/vegetablemarketexpress/product/selectProductList', {
                    "pageNo": this.currentPage,
                    "pageSize": this.pageSize,
                    "data": this.searchForm
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    }
                }).catch(function (error) {
                    console.log(error);
                    _this.$message.error('数据加载失败');
                });
            },

            // 加载分类列表
            loadCategoryList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/category/queryByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.categoryList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },

            // 加载品牌列表
            loadBrandList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/brand/queryByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.brandList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },

            // 加载单位列表
            loadUnitList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/unit/queryByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.unitList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 从JSON中提取规格名称
            getSpecData(specJson) {
                if (!specJson) return null;
                try {
                    const spec = JSON.parse(specJson);
                    // 确保返回的字段与提交时一致（specName + specValue）
                    return {
                        specName: spec.specName || '未知规格',
                        specValue: spec.specValue || '未选择值'
                    };
                } catch (e) {
                    console.error('解析规格JSON失败：', e);
                    return null;
                }
            },

            // 规格选择变化事件
            handleSpecChange(specId) {
                const spec = this.specList.find(item => item.specId === specId);
                if (spec && spec.specValues) {
                    try {
                        this.selectedSpecValues = JSON.parse(spec.specValues);
                    } catch (e) {
                        this.selectedSpecValues = spec.specValues.split(',');
                    }
                } else {
                    this.selectedSpecValues = [];
                }
                this.selectedSpecValue = '';
            },

            // 加载规格列表
            loadSpecList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/spec/queryByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.specList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            loadVarietyList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/variety/queryByParam', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.varietyList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 加载产地列表
            loadOriginList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/origin/listByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.originList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 加载等级列表
            loadGradeList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/grade/listByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.gradeList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 加载冷藏方式列表
            loadColdList() {
                let _this = this;
                axios.post('/vegetablemarketexpress/cold/listByPage', {
                    "pageNo": 1,
                    "pageSize": 1000,
                    "data": { status: '0', delFlag: '0' }
                }).then(function (response) {
                    if (response.data.code==200) {
                        _this.coldList = response.data.data.list;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadData();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },
            search() {
                this.currentPage = 1;
                this.loadData();
            },
            submitForm(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        let uri = '/vegetablemarketexpress/product/insertProduct';
                        if (this.title == '修改商品') {
                            uri = '/vegetablemarketexpress/product/updateProduct';
                        }

                        let _this = this;
                        let submitForm = JSON.parse(JSON.stringify(this.form));

                        // 提取关联对象的ID
                        if (submitForm.category) {
                            submitForm.categoryId = submitForm.category.categoryId;
                            delete submitForm.category;
                        }
                        if (submitForm.unit) {
                            submitForm.unitId = submitForm.unit.unitId;
                            delete submitForm.unit;
                        }
                        if (submitForm.brand) {
                            submitForm.brandId = submitForm.brand.brandId;
                            delete submitForm.brand;
                        }
                        if (submitForm.variety) {
                            submitForm.varietyId = submitForm.variety.varietyId;
                            delete submitForm.variety;
                        }
                        if (submitForm.origin) {
                            submitForm.originId = submitForm.origin.originId;
                            delete submitForm.origin;
                        }
                        if (submitForm.grade) {
                            submitForm.gradeId = submitForm.grade.gradeId;
                            delete submitForm.grade;
                        }
                        if (submitForm.cold) {
                            submitForm.coldId = submitForm.cold.coldId;
                            delete submitForm.cold;
                        }
                        // 处理规格JSON数据
                        if (this.selectedSpecId && this.selectedSpecValue) {
                            const selectedSpec = this.specList.find(item => item.specId === this.selectedSpecId);
                            if (selectedSpec) {
                                submitForm.specJson = JSON.stringify({
                                    specId: this.selectedSpecId,
                                    specName: selectedSpec.specName,
                                    specValue: this.selectedSpecValue
                                });
                            }
                        }

                        // 转换数值类型
                        if (submitForm.categoryId) submitForm.categoryId = parseInt(submitForm.categoryId);
                        if (submitForm.unitId) submitForm.unitId = parseInt(submitForm.unitId);
                        if (submitForm.brandId) submitForm.brandId = parseInt(submitForm.brandId);
                        if (submitForm.varietyId) submitForm.varietyId = parseInt(submitForm.varietyId);
                        if (submitForm.originId) submitForm.originId = parseInt(submitForm.originId);
                        if (submitForm.gradeId) submitForm.gradeId = parseInt(submitForm.gradeId);
                        if (submitForm.coldId) submitForm.coldId = parseInt(submitForm.coldId);
                        if (submitForm.specId) submitForm.specId = parseInt(submitForm.specId);
                        if (submitForm.price) submitForm.price = parseFloat(submitForm.price);
                        if (submitForm.minOrderQuantity) submitForm.minOrderQuantity = parseFloat(submitForm.minOrderQuantity);

                        axios.post(uri, submitForm)
                            .then(function (response) {
                                if (response.data.code==200) {
                                    _this.$message({
                                        message: '操作成功',
                                        type: 'success'
                                    });
                                    _this.loadData();
                                    _this.dialogFormVisible = false;
                                } else {
                                    _this.$message.error('操作失败');
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                _this.$message.error('操作异常');
                            });
                    } else {
                        this.$message.error('表单验证失败');
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 图片上传前处理
            beforeImageUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt5M = file.size / 1024 / 1024 < 5;

                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt5M) {
                    this.$message.error('上传图片大小不能超过 5MB!');
                    return false;
                }
                return true;
            },

            // 图片上传成功处理
            handleImageSuccess(response, file, fileList) {
                if (response.code === 200) {
                    // OssUtil 返回的 map 结构是 {filePath: "...", originName: "..."}
                    this.form.imageUrl = response.data.filePath;
                    this.$message.success('商品图片上传成功');
                } else {
                    this.$message.error('商品图片上传失败: ' + (response.msg || '未知错误'));
                }
            },

            // 图片上传失败处理
            handleImageError(err, file, fileList) {
                this.$message.error('商品图片上传失败: ' + err);
            },

            // 在 handleAdd 方法中重置图片相关数据
            handleAdd() {
                this.dialogFormVisible = true;
                this.title = "添加商品";
                this.form = {
                    productId: '',
                    productCode: '',
                    productName: '',
                    categoryId: '',
                    unitId: '',
                    brandId: '',
                    varietyId: '',
                    originId: '',
                    gradeId: '',
                    coldId: '',
                    specId: '',
                    minOrderQuantity: '',
                    price: '',
                    imageUrl: '',
                    description: '',
                    status: '0',
                    delFlag: '0',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                };
                // 清空规格选择
                this.selectedSpecId = '';
                this.selectedSpecValues = [];
                this.selectedSpecValue = '';
                // 清空文件列表
                this.imageFileList = [];
            },

            // 在 handleEdit 方法中处理已有的图片
            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.title = "修改商品";
                this.form = JSON.parse(JSON.stringify(row));

                // 规格处理
                this.selectedSpecId = '';
                this.selectedSpecValues = [];
                this.selectedSpecValue = '';

                if (row.specJson) {
                    try {
                        const specData = JSON.parse(row.specJson);
                        this.selectedSpecId = specData.specId || '';
                        this.selectedSpecValue = specData.specValue || '';
                        if (this.selectedSpecId) {
                            this.handleSpecChange(this.selectedSpecId);
                        }
                    } catch (e) {
                        console.error('解析规格JSON失败:', e);
                    }
                }

                // 图片回显
                this.imageFileList = [];
                if (this.form.imageUrl) {
                    const fileName = this.form.imageUrl.substring(this.form.imageUrl.lastIndexOf('/') + 1);
                    this.imageFileList.push({
                        name: fileName,
                        url: this.form.imageUrl
                    });
                }
            },
            // 重置表单时清空规格选择
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.selectedSpecId = '';
                this.selectedSpecValues = [];
                this.selectedSpecValue = '';
            },
            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    axios.delete('/vegetablemarketexpress/product/deleteProductById?productId=' + row.productId)
                        .then(function (response) {
                            if (response.data.code==200) {
                                _this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                _this.loadData();
                            } else {
                                _this.$message.error('删除失败');
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            _this.$message.error('删除异常');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

        }
    });
</script>
</body>
</html>
